package seentao.stdev.mobile.io.service;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.List;

import lombok.Data;

import org.springframework.stereotype.Service;

import seentao.stdev.mobile.io.vo.UrlFolder;
import seentao.stdev.mobile.util.IDGenerator;

@Service
@Data
public class UrlFolderService {
	
	private String basePath;
	private String baseUrl;
	
	public List<UrlFolder> list() {
		File base = new File(basePath);
		List<UrlFolder> data = new ArrayList<>();
		File[] files = getChildrenFolder(base);
		for (File f : files) {
			addFolders(data, f, null);
		}
		return data;
	}
	
	private void addFolders(List<UrlFolder> list, File file, String pid) {
		UrlFolder data = new UrlFolder();
		list.add(data);

		String id = IDGenerator.gen(6);
		data.setId(id);
		data.setName(file.getName());
		data.setUrl(toUrl(file.getAbsolutePath()));
		data.setPid(pid);
		File[] children = getChildrenFolder(file);
		if (children.length > 0) {
			data.setLeaf(false);
			for (File child : children) {
				addFolders(list, child, id);
			}
		} else {
			data.setLeaf(true);
		}
	}
	
	private File[] getChildrenFolder(File parent) {
		return parent.listFiles(new FileFilter() {
			@Override
			public boolean accept(File f) {
				return f.isDirectory();
			}
		});
	}

	public String toUrl(String path) {
		String url = path;
		if (url.startsWith(basePath)) {
			url = baseUrl + url.substring(basePath.length());
		}
		return url.replace("\\", "/");
	}

}
